<template>
  <div class="WriteBlog">
    <Header />
    <div class="titlebox">
      <div class="title">
        <!-- <span></span> -->
        <input type="text" placeholder="请输入标题" v-model="contentTitle" />
      </div>
    </div>
    <div class="box">
      <!-- 富文本编辑器组件 -->
      <Editor :getContent="getContent"></Editor>

      <div class="introduction">
        <div class="cover">
          <p>
            封面&摘要:
            <span>
              <input
                type="radio"
                name="picture"
                v-model="picture"
                @change="choosePicture"
                value="单图"
              />
              单图</span
            >
            <span>
              <input
                type="radio"
                name="picture"
                v-model="picture"
                @change="choosePicture"
                value="无封面"
              />无封面</span
            >
          </p>
          <!-- 上传图片 -->
          <div class="file">
            <input
              type="file"
              class="updata"
              accept="image/*"
              @change="change($event)"
              ref="updata"
            />
            <img
              :src="imageUrl ? imageUrl : baseImg"
              alt=""
              class="img"
              ref="fileImg"
            />

            <textarea
              name=""
              id=""
              cols="50"
              rows="5"
              placeholder="摘要（选填）：会在推荐、列表等场景外露，帮助读者快速了解内容"
              v-model="fileTextareaValue"
              ref="fileTextarea"
              style="padding: 5px 20px"
            ></textarea>
          </div>
        </div>

        <div class="label">
          文章标签:

          <el-select
            style="margin-left: 25px"
            v-model="labelvalue"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              style="padding: 10px 30px"
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>

        <div class="classify">
          分类专栏:
          <div class="block" style="margin-top: -50px; margin-left: 20px">
            <el-cascader
              v-model="classifyvalue"
              :options="classifyoptions"
              @change="handleChange"
            ></el-cascader>
          </div>
        </div>

        <div class="type">
          <p>
            文章类型:
            <span>
              <input type="radio" name="article" value="1" v-model="type" />
              原创</span
            >
            <span>
              <input
                type="radio"
                name="article"
                v-model="type"
                value="0"
              />转载</span
            >
          </p>
        </div>

        <div class="modality">
          <p>
            发布形式:
            <span>
              <input type="radio" name="private" v-model="modality" value="1" />
              公开</span
            >
            <span>
              <input
                type="radio"
                name="private"
                v-model="modality"
                value="0"
              />私密</span
            >
          </p>
        </div>
      </div>
    </div>

    <div class="fixed">
      <span @click="SaveDrafts">保存草稿</span>
      <span @click="publishBlog">发布博客</span>
      <p class="realTime">博客实时保存于 {{ realTime }}</p>
    </div>
    <!-- 提示信息 -->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <span
        >您有博客未保存，请问是否继续编写？如选择不继续编写将失去原来的博客!</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          plain
          @click="centerDialogVisible = false"
          class="btn"
          >继续编写</el-button
        >
        <el-button
          type="primary"
          @click="
            isClearPage();
            centerDialogVisible = false;
          "
          class="btn"
          >创建新博客</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Header from "../../components/Header.vue";
import Editor from "../../components/BlogComponents/Editor";
import { mixin } from "../../mixin";
export default {
  props: {
    /*编辑器的内容*/
    value: {
      type: String,
    },
    /*图片大小*/
    maxSize: {
      type: Number,
      default: 4000, //kb
    },
  },
  name: "WriteBlog",
  //混入，引入时间戳处理函数
  mixins: [mixin],
  data() {
    return {
      //提示博客信息
      centerDialogVisible: false,
      //博客实施保存保存时间
      realTime: "",
      // 博客id
      id: "",
      // 发布形式
      modality: "",
      // 文章类型
      type: "",
      // 摘要
      fileTextareaValue: "",
      // 默认封面
      picture: "单图",
      // 博客内容
      blogContent: "",
      // 博客标题
      contentTitle: "",
      // 上传的图片
      imageUrl: "",
      // 默认的图片
      baseImg: "",
      // 文章标签组件element
      options: [],
      labelvalue: [],
      list: [],
      loading: false,
      states: [],
      // 文章类型组件element
      classifyvalue: [],
      classifyoptions: [],
      //监视浏览器
      beforeUnloadTime: "",
      gapTime: "",
      timer: "", //设定全局定时器
    };
  },
  // 获取组件
  components: {
    Header,
    Editor,
  },
  computed: {},
  // 上传图片
  mounted() {
    // 接收编辑博客的id
    if (this.$route.query.id) {
      this.$http({
        method: "post",
        url: "article/intoEditArticle",
        params: {
          article_id: this.$route.query.id, //博客id
        },
      }).then(({ data }) => {
        // console.log(data);
        this.id = data.data.article.article_id; //博客id
        this.contentTitle = data.data.article.article_title; //标题
        this.blogContent = data.data.article.article_content; //博客正文
        this.imageUrl = data.data.article.article_picture; //文章封面
        this.fileTextareaValue = data.data.article.article_summary; //文章摘要
        this.modality = data.data.article.article_public_status; //文章发布形式
        this.type = data.data.article.original_or_reprint; //文章发布形式
        //从数据库中获取到标签并存入到labelvalue中
        for (var i = 0; i < data.data.tags.length; i++) {
          this.labelvalue.push(`${data.data.tags[i].tag_name}`);
        }
        //从数据库中取出文章类型并存入到classifyvalue中
        var a = [];
        a.push(data.data.category.categoryThird.category_name);
        a.push(data.data.category.categorySecond.category_name);
        a.push(data.data.category.categoryFirst.category_name);
        this.classifyvalue = a;
        console.log(this.classifyvalue);

        // 编辑草稿或已发表的博客时判断有无封面
        if (data.data.article.article_picture) {
          // 是单图就让上传图片的盒子显示出来，并调动文本框的位置
          this.picture = "单图";
          this.$refs.updata.style.display = "block";
          this.$refs.fileImg.style.display = "block";
          this.$refs.fileTextarea.style.marginLeft = "0px";
        } else {
          // 是无封面就让上传图片的盒子隐藏出来，并调动文本框的位置
          this.picture = "无封面";
          this.$refs.updata.style.display = "none";
          this.$refs.fileImg.style.display = "none";
          this.$refs.fileTextarea.style.marginLeft = "-200px";
        }
        // 全局事件总线传递博客内容到Editor组件中
        this.$bus.$emit("value", this.blogContent);
      });
    } else {
      //否则发送实时存储的初始化请求
      this.RealTimeStorage("abc");
    }
    // 选择封面
    if (this.picture == "无封面") {
      // 是无封面就让上传图片的盒子隐藏出来，并调动文本框的位置
      this.$refs.updata.style.display = "none";
      this.$refs.fileImg.style.display = "none";
      this.$refs.fileTextarea.style.marginLeft = "-200px";
    } else {
      // 是单图就让上传图片的盒子显示出来，并调动文本框的位置
      this.$refs.updata.style.display = "block";
      this.$refs.fileImg.style.display = "block";
      this.$refs.fileTextarea.style.marginLeft = "0px";
      // console.log(0);
    }
    // 获取数据库中的标签与类型
    this.$http({
      method: "post",
      url: "article/userWriteArticle",
    }).then(({ data }) => {
      if (data.flag) {
        console.log(data);
        // 将数据库中的标签存入到变量tag中
        const tag = data.data.tags;
        // 将数据库中的文章类型存入到变量categories中
        const categories = data.data.categories;
        // 将变量tags中的标签遍历存入到states数组中
        for (var i = 0; i < tag.length; i++) {
          this.states.push(tag[i].tag_name);
        }
        // 展示文章标签(element-ui固定写法)
        this.list = this.states.map((item) => {
          return { value: `${item}`, label: `${item}` };
        });
        //文章类型
        // 将数据库中获取到的文章类型转为数组
        const arr1 = Object.keys(categories);
        var valArr = arr1.map(function (i) {
          return categories[i];
        });
        // 遍历第一层并获取
        for (let i = 0; i < arr1.length; i++) {
          this.classifyoptions.push({});
          this.classifyoptions[i].value = arr1[i];
          this.classifyoptions[i].label = arr1[i];
          this.classifyoptions[i].children = [];
          const aa = Object.keys(valArr[i]); //第二层的key
          const bb = aa.map(function (k) {
            return valArr[i][k];
          }); //第二层的key
          // 遍历第二层并获取
          for (var j = 0; j < aa.length; j++) {
            this.classifyoptions[i].children.push({});
            this.classifyoptions[i].children[j].value = aa[j];
            this.classifyoptions[i].children[j].label = aa[j];
            this.classifyoptions[i].children[j].children = [];
            // 遍历第三层并获取
            for (var n = 0; n < bb[j].length; n++) {
              this.classifyoptions[i].children[j].children.push({});
              this.classifyoptions[i].children[j].children[n].value = bb[j][n];
              this.classifyoptions[i].children[j].children[n].label = bb[j][n];
            }
          }
        }
      } else {
        this.$message.warning(data.errorMsg);
      }
    });
    window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
    //设定定时器
    this.myclick();
  },

  methods: {
    //检测浏览器关闭或者刷新
    beforeunloadHandler(e) {
      this._beforeUnload_time = new Date().getTime();
      e = e || window.event;
      if (e) {
        e.returnValue = "关闭提示";
      }
      return "关闭提示";
    },
    // 选择封面
    choosePicture() {
      if (this.picture == "无封面") {
        // 是无封面就让上传图片的盒子隐藏出来，并调动文本框的位置
        console.log(1);
        this.$refs.updata.style.display = "none";
        this.$refs.fileImg.style.display = "none";
        this.$refs.fileTextarea.style.marginLeft = "-200px";
      } else {
        // 是单图就让上传图片的盒子显示出来，并调动文本框的位置
        this.$refs.updata.style.display = "block";
        this.$refs.fileImg.style.display = "block";
        this.$refs.fileTextarea.style.marginLeft = "0px";
        console.log(0);
      }
    },
    // // 分类专栏组件element
    handleChange(value) {
      console.log(value);
    },
    // 文章标签组件(element-ui固定写法)
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 保存草稿
    SaveDrafts() {
      // 连接服务器
      if (
        this.labelvalue.length  &&
        this.classifyvalue.length &&
        this.contentTitle
      ) {
        let url1 = "article/userSaveArticle";
        let obj1 = {
          article_title: this.contentTitle, //博客标题
          article_content: this.blogContent, //博客内容
          article_status: 0, //发布还是存草稿
          article_picture: this.imageUrl, //封面图片
          article_public_status: this.modality, //发布形式，公开or私密
          article_summary: this.fileTextareaValue, //摘要
          original_or_reprint: this.type, //文章类型，原创or转载
        };
        if (this.$route.query.id) {
          obj1.article_id = this.$route.query.id;
          url1 = "article/saveEditArticle";
        }
        this.$http({
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          url: `${url1}?tags=${this.labelvalue}&category_name=${this.classifyvalue}`,
          data: JSON.stringify(obj1),
        }).then(({ data }) => {
          console.log(data);
          if (data.flag) {
            // 登录成功进行路由跳转
            console.log(data.data);
            console.log("草稿上传成功");
            this.$message.success("保存草稿成功");
            // 保存成功之后进行页面的跳转
            this.$router.push({
              name: "Drafts",
            });
          } else {
            // 发表失败展示错误信息
            console.log("草稿上传失败");
            this.$message.warning("保存草稿失败");
          }
        });

        console.log("发布了标题", this.contentTitle);
        console.log("发布了博客内容", this.blogContent);
        if (this.picture == "单图") {
          console.log("发布封面", this.imageUrl);
        } else {
          console.log("无封面");
        }
        console.log("发布了摘要", this.fileTextareaValue);
        console.log("发布文章标签", this.labelvalue);
        console.log("发布分类专栏", this.classifyvalue);

        console.log("发布文章类型", this.type);
        console.log("发布了发布形式", this.modality);
      } else {
        this.$message.warning("请填写文章类型、分类专栏和标题");
      }
    },
    // 发布博客
    publishBlog() {
      // 博客的所有内容不能为空
      if (
        this.contentTitle &&
        this.blogContent &&
        this.fileTextareaValue &&
        this.labelvalue &&
        this.classifyvalue &&
        this.type != null &&
        this.modality != null
      ) {
        let url2 = "article/userSaveArticle";
        let obj2 = {
          article_title: this.contentTitle, //博客标题
          article_content: this.blogContent, //博客内容
          article_status: 2, //博客状态改为审核中
          article_picture: this.imageUrl, //封面图片
          article_public_status: this.modality, //发布形式，公开or私密
          article_summary: this.fileTextareaValue, //摘要
          original_or_reprint: this.type, //文章类型，原创or转载
        };
        if (this.$route.query.id) {
          obj2.article_id = this.$route.query.id;
          url2 = "article/saveEditArticle";
        }
        this.$http({
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          // 允许跨域
          url: `${url2}?tags=${this.labelvalue}&category_name=${this.classifyvalue}`,
          data: JSON.stringify(obj2),
        }).then(({ data }) => {
          console.log(data);
          if (data.flag) {
            // 登录成功进行路由跳转
            console.log(data.data);
            console.log("博客上传成功");
            this.$message.success("提交审核成功！请等候博客审核...");
            // 博客发表成功之后进行页面的跳转
            this.$router.push({
              name: "PersonalCenter",
            });
          } else {
            // 发表失败展示错误信息
            this.$message.warning("博客发布失败!");
          }
        });
      } else {
        this.$message.warning("请把所有内容填写完整！");
      }
    },
    //发布数据库已经存在的博客
    releaseBlog() {},
    // 收到了富文本编辑器中的内容
    getContent(content) {
      // console.log("收到了内容：", content);
      this.blogContent = content;
    },
    change(e) {
      console.log(e.target.files[0].name);
      // 判断是不是规定格式
      // let name  =  e.target.files[0].name

      // 获取到第一张图片
      let file = e.target.files[0];

      // 创建文件读取对象
      var reader = new FileReader();
      var that = this;

      //  将文件读取为DataURL
      reader.readAsDataURL(file);

      // 读取成功调用方法
      reader.onload = (e) => {
        console.log("读取成功");

        // e.target.result 获取 读取成功后的  文件DataURL
        that.imageUrl = e.target.result;

        // 如果要将图片上传服务器，就在这里调用后台方法
      };
    },
    //实时存储初始化
    RealTimeStorage(status) {
      let str = `tags=${this.labelvalue}&category_name=${this.classifyvalue}`;
      if (status) {
        str = str + `&status=11`;
      }
      let obj = {
        article_title: this.contentTitle, //博客标题
        article_content: this.blogContent, //博客内容
        article_status: 0, //发布还是存草稿
        article_picture: this.imageUrl, //封面图片
        article_public_status: this.modality, //发布形式，公开or私密
        article_summary: this.fileTextareaValue, //摘要
        original_or_reprint: this.type, //文章类型，原创or转载
      };
      this.$http({
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        url: `article/realTimeSave?${str}`,
        data: JSON.stringify(obj),
      }).then(({ data }) => {
           console.log("实施保存", data);
        if (data.flag) {
       
          //文章数据处理
          if (status && data.data.articleDataMap) {
            this.id = data.data.articleDataMap.article.article_id; //博客id
            this.contentTitle = data.data.articleDataMap.article.article_title; //标题
            this.blogContent = data.data.articleDataMap.article.article_content; //博客正文
            this.imageUrl = data.data.articleDataMap.article.article_picture; //文章封面
            this.fileTextareaValue =
              data.data.articleDataMap.article.article_summary; //文章摘要
            this.modality =
              data.data.articleDataMap.article.article_public_status; //文章发布形式
            this.type = data.data.articleDataMap.article.original_or_reprint; //文章发布形式
            //从数据库中获取到标签并存入到labelvalue中
            for (var i = 0; i < data.data.articleDataMap.tags.length; i++) {
              this.labelvalue.push(`${data.data.articleDataMap.tags[i]}`);
            }
            //从数据库中取出文章类型并存入到classifyvalue中
            var a = [];
            a.push(data.data.articleDataMap.category_name[0]);
            a.push(data.data.articleDataMap.category_name[1]);
            a.push(data.data.articleDataMap.category_name[2]);
            this.classifyvalue = a;
            // 编辑草稿或已发表的博客时判断有无封面
            if (data.data.articleDataMap.article.article_picture) {
              // 是单图就让上传图片的盒子显示出来，并调动文本框的位置
              this.picture = "单图";
              this.$refs.updata.style.display = "block";
              this.$refs.fileImg.style.display = "block";
              this.$refs.fileTextarea.style.marginLeft = "0px";
            } else {
              // 是无封面就让上传图片的盒子隐藏出来，并调动文本框的位置
              this.picture = "无封面";
              this.$refs.updata.style.display = "none";
              this.$refs.fileImg.style.display = "none";
              this.$refs.fileTextarea.style.marginLeft = "-200px";
            }
            //判断数据是否存在并且提示
            if (
              this.id ||
              this.imageUrl ||
              this.contentTitle ||
              this.blogContent ||
              this.fileTextareaValue ||
              this.labelvalue.length > 0 ||
              this.classifyvalue[0] ||
              this.type ||
              this.modality
            ) {
              this.centerDialogVisible = true;
            }
            // 全局事件总线传递博客内容到Editor组件中
            this.$bus.$emit("RealTimeStorage", this.blogContent);
          } else {
            // 全局事件总线传递博客内容到Editor组件中
            this.$bus.$emit("RealTimeStorage", this.blogContent);
            //更新实时保存时间
            this.realTime = this.formatDate(Date.now());
          }
        } else {
          // 发表失败展示错误信息
          this.$message({
            message: `${data.errorMsg}`,
            type: "warning",
            offset: 100,
            duration: 2000,
            center: true,
            customClass: "showstyle",
          });
        }
      });
    },
    //设置实时保存定时器
    myclick() {
      this.timer = setInterval(() => {
        this.RealTimeStorage();
      }, 10000);
    },
    //清空页面方法
    isClearPage() {
      //清空所有信息
      this.id = "";
      this.imageUrl = "";
      this.contentTitle = "";
      this.blogContent = "";
      this.fileTextareaValue = "";
      this.labelvalue = "";
      this.classifyvalue = "";
      this.type = "";
      this.modality = "";
      // 全局事件总线传递博客内容到Editor组件中
      // this.$bus.$emit("RealTimeStorage", this.blogContent);
      //重新保存
      this.RealTimeStorage();
    },
  },
  created() {
    // 获取默认显示的图片
    this.baseImg = require("../../assets/moren.png");
    //更新实时保存时间
    this.realTime = this.formatDate(Date.now());
  },
  beforeDestroy() {
    //销毁定时器
    clearInterval(this.timer);
    this.timer = null;
  },
};
</script>
<style lang="less">
.btn {
  padding: 5px !important;
}
.showstyle {
  min-width: 30px !important;
  padding: 10px 10px 10px 15px;
}
</style>
<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.box {
  margin-top: 20px;
  width: 100%;
  height: 1200px;
  /* background-image: url(../assets/newbg.png); */

  /* background-color: skyblue; */
}
.quill-editor {
  height: 500px;
  width: 80%;
  margin-left: 10%;
}
.introduction {
  width: 80%;
  height: 480px;
  box-shadow: 0 0 10px 0px rgb(219, 218, 218);
  border: 1px solid #fff;
  /* background-color: rgb(60, 157, 196); */
  margin-top: 100px;
  margin-left: 10%;
  /* opacity: 0.5; */
}
.introduction div {
  width: 80%;
  margin-left: 10%;
}
.titlebox {
  margin-top: 20px;
  margin-left: 10%;
  width: 80%;
  height: 80px;
  border-radius: 80px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #fff;
  box-shadow: 0 0 10px 0px rgb(219, 218, 218);
}
.title {
  margin-top: 20px;
  height: 50px;
  text-align: center;
  line-height: 50px;
}
/* .title span {
  margin-left: 85px; 
   font-size: large;
 }  */
.title input {
  font-size: x-large;
  border: none;
  outline: none;
  height: 25px;
  width: 100%;

  text-align: center;
  /* margin-left: 200px; */
}
.cover {
  margin-top: 50px;
  height: 150px;
}
.cover p span {
  margin-left: 25px;
  margin-right: 30px;
}

.file {
  position: relative;

  width: 150px !important;
  height: 100px !important;
  /* background-color: #ccc; */
}
.file input {
  width: 150px;
  height: 100px;
  margin-bottom: 15px;
}
.updata {
  display: block;
  height: 100%;
  width: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.img {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 150px;
  height: 100px;
}
.cover p {
  margin-bottom: 15px;
}
.cover textarea {
  position: absolute;
  resize: none;
  left: 200px;
  top: 10px;
  height: 100px;
  outline: none;
  border: 1px solid #ccc;
}
.classify {
  margin-top: 15px;
  height: 50px;
  line-height: 50px;
}

.type {
  margin-top: 35px;
}
.type p span {
  margin-left: 25px;
  margin-right: 30px;
}

.modality p {
  margin-top: 35px;
}
.modality p span {
  margin-left: 25px;
  margin-right: 30px;
}
.label {
  margin-top: 15px;
  position: relative;
  height: 50px;
  line-height: 50px;
}

.label span {
  text-align: center;
  line-height: 25px;
  display: inline-block;
  border: 1px solid #ccc;
  width: 150px;
  height: 25px;
  margin-left: 20px;
}

.fixed {
  line-height: 100px;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 100px;
  /* border-top: 1px solid skyblue; */
  background-color: rgb(244, 244, 244);
  .realTime {
    position: absolute;
    bottom: 10px;
    right: 10px;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
  }
}
.fixed span {
  display: inline-block;
  width: 100px;
  height: 40px;
  border: 2px solid skyblue;
  text-align: center;
  line-height: 40px;
  border-radius: 25%;
  cursor: pointer;
}
.fixed span:hover {
  background-color: skyblue;
}

.fixed span:first-child {
  margin-left: 30%;
  margin-right: 20%;
}
/* .fixed span:last-child {
  background-color: skyblue;
} */
</style>